#!/usr/bin/evn python
# coding=utf-8
from typing import List, Dict

from peewee import fn

from afast_core.core_tools.encrypt_helper import md5
from infirmary_admin_src.infirmary_smart_admin.infirmary_models.admin_dbhelper import session_scope, \
    session_scope_atomic, JOIN
from infirmary_admin_src.infirmary_smart_admin.infirmary_models.admin_model import SysEmployee, SysMenu, \
    SysRoleEmployee, SysRole, SysDept
from infirmary_admin_src.infirmary_smart_admin.infirmary_utils.department_help import convert_data


class EmployeeBusinesses:
    pass

    @classmethod
    def get_sys_employee_id_max_id(cls):
        '''
        添加职务
        :param role_id:
        :return:
        '''
        with session_scope():
            return SysEmployee.select(fn.MAX(SysEmployee.employee_id)).scalar()

    @classmethod
    def add_sys_employee_and_role(cls, roleIdLists, **kwargs):
        with session_scope():
            if roleIdLists:
                for ridv in roleIdLists:
                    id_max_id = SysRoleEmployee.select(fn.MAX(SysRoleEmployee.id)).scalar() + 1
                    SysRoleEmployee.create(
                        id=id_max_id,
                        role_id=ridv,
                        employee_id= kwargs.get('employee_id'),
                        create_time='now()',
                        update_time='now()',
                    )
            return SysEmployee.get_or_create(**kwargs)

    @staticmethod
    def get_sys_employee_info_by_login_name(login_name) -> SysEmployee:
        with session_scope():
            return SysEmployee.get_or_none(SysEmployee.login_name == login_name, SysEmployee.deleted_flag == 0)


    @staticmethod
    def get_sys_employee_all_listi():
        with session_scope():
            _result = SysEmployee.select(
                SysEmployee.actual_name,
                SysEmployee.administrator_flag,
                SysEmployee.create_time,
                SysEmployee.department_id,
                SysEmployee.disabled_flag,
                SysEmployee.employee_id,
                SysEmployee.gender,
                SysEmployee.login_name,
                SysEmployee.phone,
            ).dicts().where(SysEmployee.deleted_flag == 0)
            # 避免多次查询数据库
            # 查询当前用户角色表信息---匹配用户角色信息
            allroleinfo = {
                v.get('role_id'): v.get('role_name')
                for v in SysRole.select().dicts()}

            employee_id_roleinfo = {}

            def ckasm(v):
                employee_id_roleinfo.setdefault(v.get('employee_id'), [])
                employee_id_roleinfo[v.get('employee_id')].append(v.get('role_id'))
                return v

            # 角色用户表字典数据
            alluserinfo = [ckasm(v) for v in
                           SysRoleEmployee.select(SysRoleEmployee.employee_id, SysRoleEmployee.role_id).dicts()]

            # 获取部门ID 串联长的部门信息表

            alldeptinfo = convert_data([v for v in SysDept.select().dicts()])

            alldeptinfodict = {
                v.get('department_id'): v.get('name')
                for v in alldeptinfo
            }

            # 匹配查询用户数据，获取对应的用户的 角色和部分等信息
            def makeuser_for_role(v):
                if v.get('employee_id') in employee_id_roleinfo:
                    v['roleIdList'] = employee_id_roleinfo[v.get('employee_id')]
                    # 根据角色ID 获取角色名称
                    v['roleNameList'] = []
                    for rv in v['roleIdList']:
                        pass
                        # 从角色字典中获取角色名称信息
                        v['roleNameList'].append(allroleinfo[rv])
                    v['roleNameList'] = ','.join(v['roleNameList'])
                else:
                    v['roleIdList'] = []
                    v['roleNameList'] = []

                if v.get('department_id') in alldeptinfodict:
                    v['departmentName'] = alldeptinfodict[v.get('department_id')]
                else:
                    v['departmentName'] = "暂无部门归属"
                return v
            return [makeuser_for_role(v) for v in _result]

    @staticmethod
    def get_sys_employee_List_by_admin_role() -> List[SysEmployee]:
        with session_scope():
            return [v for v in SysEmployee.select().dicts()]

    @classmethod
    def edit_sys_employee_singe(cls, employee_id, **kwargs):
        with session_scope():
            return SysEmployee.update(**kwargs).where(SysEmployee.employee_id == employee_id, ).execute()

    @classmethod
    def edit_sys_employee_update_disabled(cls, employee_id):
        with session_scope():
            result = SysEmployee.get_or_none(SysEmployee.employee_id == employee_id)
            if result.disabled_flag == 1:
                result.disabled_flag = 0
            else:
                result.disabled_flag = 1
            return SysEmployee.update(disabled_flag=result.disabled_flag).where(
                SysEmployee.employee_id == employee_id).execute()

    @classmethod
    def edit_sys_employee_password_reset(cls, employee_id):
        with session_scope():
            return SysEmployee.update(login_pwd=md5('zyg123456').lower()).where(
                SysEmployee.employee_id == employee_id).execute()

    @classmethod
    def edit_sys_employee_for_role_singe(cls, employee_id, roleIdList):
        with session_scope():
            SysRoleEmployee.delete().where(SysEmployee.employee_id == employee_id, ).execute()
            if roleIdList:
                for ridv in roleIdList:
                    SysRoleEmployee.create(role_i=ridv,
                                           employee_id=employee_id,
                                           create_time='now()',
                                           update_time='now()',
                                           )

            return True

    @classmethod
    def edit_sys_employee_update_batch_department(cls, department_id, employee_id_lists):
        with session_scope():
            return SysEmployee.update(department_id=department_id).where(
                SysEmployee.employee_id.in_(employee_id_lists)).execute()

    @classmethod
    def edit_sys_employee_update_del_batch(cls,employee_id_lists, deleted_flag=1):
        with session_scope():
            return SysEmployee.update(deleted_flag=deleted_flag).where(
                SysEmployee.employee_id.in_(employee_id_lists)).execute()

    @classmethod
    def edit_sys_employee_and_role(cls, employee_id, roleIdList, **kwargs):
        with session_scope():
            SysRoleEmployee.delete().where(SysRoleEmployee.employee_id == employee_id).execute()
            if roleIdList:
                for ridv in roleIdList:
                    id_max_id = SysRoleEmployee.select(fn.MAX(SysRoleEmployee.id)).scalar() + 1
                    SysRoleEmployee.create(
                        id=id_max_id,
                        role_id=ridv,
                        employee_id=employee_id,
                        create_time='now()',
                        update_time='now()',
                    )
            return SysEmployee.update(**kwargs).where(SysEmployee.employee_id == employee_id, ).execute()

    @staticmethod
    def get_sys_employee_authorities_by_admin_role() -> List[Dict]:
        with session_scope():
            return [{
                'authority': v.get('web_perms')
            } for v in SysMenu.select(SysMenu.web_perms).where(SysMenu.menu_type == 3,
                                                               SysMenu.disabled_flag == 0).dicts().order_by(
                SysMenu.create_time.desc())]

    @staticmethod
    def get_sys_role_admin() -> Dict:
        with session_scope():
            return {
                v.get('role_id'): v.get('role_name')
                for v in SysRole.select().dicts()}

    @staticmethod
    def get_sys_employee_List_by_admin_role_infos(keyword=None, department_id=None, disabled_flag=False, pageNum=1,
                                                  pageSize=10):
        with session_scope():
            # 获取所有的用户信息列表
            # 条件的表达式的串联
            def curr_expression():
                exprsopm = SysEmployee.deleted_flag == 0

                if keyword:
                    exprsopm = (exprsopm & (SysEmployee.actual_name.contains(keyword))) if exprsopm else (
                        SysEmployee.actual_name.contains(keyword))

                if department_id and department_id != 1:
                    exprsopm = (exprsopm & (SysEmployee.department_id == department_id)) if exprsopm else (
                            SysEmployee.department_id == department_id)

                if disabled_flag:
                    exprsopm = (exprsopm & (SysEmployee.disabled_flag == 1 if disabled_flag else 0)) if exprsopm else (
                        SysEmployee.disabled_flag == 1 if disabled_flag else 0)

                return exprsopm

            _result_query = SysEmployee.select(
                SysEmployee.actual_name,
                SysEmployee.create_time,
                SysEmployee.deleted_flag,
                SysEmployee.department_id,
                SysEmployee.disabled_flag,
                SysEmployee.employee_id,
                SysEmployee.gender,
                SysEmployee.login_name,
                SysEmployee.phone,
                SysEmployee.administrator_flag,
                SysEmployee.update_time,

            ).where(curr_expression())
            _result_nums_total = _result_query.count()

            # 如果没有数据直接的不在进行分页查找
            if _result_nums_total > 0:
                _result = _result_query.paginate(pageNum, pageSize) \
                    .dicts() \
                    .order_by(SysEmployee.employee_id)

                if not _result:
                    # 把对应的结果保存到缓存中---缓存穿透：处理
                    return 0, []  # 查询没有结果的时候
                # 合并返回新的字典信息

                # 避免多次查询数据库
                # 查询当前用户角色表信息---匹配用户角色信息
                allroleinfo = {
                    v.get('role_id'): v.get('role_name')
                    for v in SysRole.select().dicts()}

                employee_id_roleinfo = {}

                def ckasm(v):
                    employee_id_roleinfo.setdefault(v.get('employee_id'), [])
                    employee_id_roleinfo[v.get('employee_id')].append(v.get('role_id'))
                    return v

                # 角色用户表字典数据
                alluserinfo = [ckasm(v) for v in
                               SysRoleEmployee.select(SysRoleEmployee.employee_id, SysRoleEmployee.role_id).dicts()]

                # 获取部门ID 串联长的部门信息表

                alldeptinfo = convert_data([v for v in SysDept.select().dicts()])

                alldeptinfodict = {
                    v.get('department_id'): v.get('name')
                    for v in alldeptinfo
                }

                # 匹配查询用户数据，获取对应的用户的 角色和部分等信息
                def makeuser_for_role(v):
                    if v.get('employee_id') in employee_id_roleinfo:
                        v['roleIdList'] = employee_id_roleinfo[v.get('employee_id')]
                        # 根据角色ID 获取角色名称
                        v['roleNameList'] = []
                        for rv in v['roleIdList']:
                            pass
                            # 从角色字典中获取角色名称信息
                            v['roleNameList'].append(allroleinfo[rv])
                        v['roleNameList'] = ','.join(v['roleNameList'])
                    else:
                        v['roleIdList'] = []
                        v['roleNameList'] = []

                    if v.get('department_id') in alldeptinfodict:
                        v['departmentName'] = alldeptinfodict[v.get('department_id')]
                    else:
                        v['departmentName'] = "暂无部门归属"
                    return v

                return _result_nums_total, [makeuser_for_role(v) for v in _result]
        return 0, None  # 查询没有结果的时候

    @staticmethod
    def get_sys_employee_List_by_admin_role_infos_roleinfo(keyword=None, department_id=None, disabled_flag=False,
                                                           pageNum=1,
                                                           pageSize=10):
        with session_scope():
            # 获取所有的用户信息列表
            # 条件的表达式的串联
            def curr_expression():
                exprsopm = SysEmployee.deleted_flag == 0

                if keyword:
                    exprsopm = (exprsopm & (SysEmployee.actual_name.contains(keyword))) if exprsopm else (
                        SysEmployee.actual_name.contains(keyword))

                if department_id:
                    exprsopm = (exprsopm & (SysEmployee.department_id == department_id)) if exprsopm else (
                            SysEmployee.department_id == department_id)

                if disabled_flag:
                    exprsopm = (exprsopm & (SysEmployee.disabled_flag == 1 if disabled_flag else 0)) if exprsopm else (
                        SysEmployee.disabled_flag == 1 if disabled_flag else 0)

                return exprsopm

            _result_query = SysEmployee.select(SysEmployee,
                                               SysRoleEmployee.role_id.alias('roleIdList'),
                                               SysRole.role_name.alias('roleNameList')
                                               ) \
                .join(SysRoleEmployee, JOIN.LEFT_OUTER, on=(SysEmployee.employee_id == SysRoleEmployee.employee_id)) \
                .join(SysRole, JOIN.LEFT_OUTER, on=(SysRoleEmployee.role_id == SysRole.role_id)) \
                .where(curr_expression())
            _result_nums_total = _result_query.count()

            # 如果没有数据直接的不在进行分页查找
            if _result_nums_total > 0:
                _result = _result_query.paginate(pageNum, pageSize) \
                    .dicts() \
                    .order_by(SysEmployee.employee_id)

                if not _result:
                    # 把对应的结果保存到缓存中---缓存穿透：处理
                    return 0, []  # 查询没有结果的时候
                # 合并返回新的字典信息

                #

                return _result_nums_total, [v for v in _result]
        return 0, None  # 查询没有结果的时候
